import React from 'react'
import {
  Text,
  View,
  StyleSheet,
  Easing,
  Animated,
  InteractionManager
} from 'react-native'

const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    justifyContent: 'center'
  },
  text: {
    color: '#c5c6c7',
    fontFamily: 'iconfont',
    backgroundColor: 'transparent',
    position: 'relative'
  },
  textCenter: {
    color: '#c5c6c7',
    fontFamily: 'iconfont',
    position: 'absolute'
  }
})

class RzLoading extends React.Component {
  constructor (props) {
    super(props)
    this.displayName = 'RzLoading'
    this.state = {
      rotation: new Animated.Value(0),
      startRotating: true,
      animateCount: 0
    }

    this.startAnimation = this.startAnimation.bind(this)
    this.stopAnimation = this.stopAnimation.bind(this)
  }

  componentDidMount () {
    this.startAnimation()
  }

  componentWillReceiveProps (nextProps) {
    const {
      startRotating
    } = nextProps
    if (startRotating) {
      this.startAnimation()
    }
  }

  componentWillUnmount () {
    console.log('===移除动画==')
    this.state.rotation.removeAllListeners()
    this.state.rotation.stopAnimation()
  }

  startAnimation () {
    this.state.rotation.setValue(0)
    InteractionManager.runAfterInteractions(() => {
      Animated.timing(this.state.rotation, {
        toValue: 1,
        duration: 1200000,
        easing: Easing.linear
      }).start()
    })
  }

  stopAnimation () {
    this.state.rotation.stopAnimation(({ value }) => {
      if (this.props.stopFunc) {
        this.props.stopFunc(value.toFixed(2))
      }
    })
  }
// &#xe66c;
  render () {
    return (
      <View
        style={[styles.container, {
          height: this.props.loadingWH,
          width: this.props.loadingWH
        }, this.props.style]}
      >
        <Text
          style={[styles.textCenter, {
            fontSize: this.props.loadingWH / 2,
            left: this.props.loadingWH / 4,
            top: this.props.loadingWH / 4,
            height: this.props.loadingWH / 2 }]}
        >
          &#xe66c;
        </Text>
        <Animated.View
          style={[styles.container, {
            transform: [{
              rotateZ: this.state.rotation.interpolate({
                inputRange: [0, 1],
                outputRange: ['0deg', '360000deg']
              })
            }]
          }]}
        >
          <Text style={[styles.text, { fontSize: this.props.loadingWH, height: this.props.loadingWH }]}>&#xe678;</Text>
        </Animated.View>
      </View>
    )
  }
}

RzLoading.propTypes = {
  loadingWH: React.PropTypes.number.isRequired,
  startFunc: React.PropTypes.func,
  stopFunc: React.PropTypes.func
  // startRotating: React.PropTypes.bool,
}

RzLoading.defaultProps = {
  loadingWH: 80
  // startRotating: true,
}

export default RzLoading
